<template>
  <div class="w-screen h-screen p-3 box-border">
    <div class="flex w-full h-full">
      <div class="flex-[2] relative">
        <div
          class="flex bg-blue-200/15 px-4 h-16 box-border rounded items-center justify-start text-base text-[#333] font-bold">
          <div class="flex items-center justify-center">
            <el-form :inline="true">
              <el-form-item label="模式">
                <el-select v-model="modeValue" placeholder="请选择" @change="handleModeChange" style="width: 100px">
                  <el-option v-for="item in modeList" :key="item.idx" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
              <el-form-item label="分辨率">
                <el-select v-model="resolutionValue" placeholder="请选择" @change="handleResolutionChange"
                  style="width: 120px">
                  <el-option v-for="(item, index) in resolutionList" :key="index"
                    :label="item.width + 'x' + item.height" :value="item.width + 'x' + item.height" />
                </el-select>
              </el-form-item>
              <el-form-item label="图片角度">
                <el-select v-model="angleValue" placeholder="请选择图片角度" @change="handleAngleChange" style="width: 100px">
                  <el-option label="0度" value="0" />
                  <el-option label="90度" value="1" />
                  <el-option label="180度" value="2" />
                  <el-option label="270度" value="3" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div
          class="absolute top-[76px] left-0 bottom-[108px] w-full bg-blue-200/15 rounded flex items-center justify-center">
          <div class="absolute top-3 left-3 text-center text-sm text-[#333] font-bold">
            当前动作：{{ actionValue || "-" }}
          </div>
          <canvas ref="videoCanvas" id="videoCanvas" width="640" height="480" class="bg-gray-500/10 rounded"
            @mousemove="handleMouseMove" @mouseleave="handleMouseLeave" @mousedown="handleMouseDown"
            @mouseup="handleMouseUp"></canvas>
        </div>
        <div class="flex justify-between absolute bottom-0 left-0 right-0">
          <div class="flex flex-1 bg-blue-200/15 p-4 box-border rounded items-center justify-start">
            <!-- 遮罩层 -->
            <div v-if="!isMaskShow" class="absolute top-0 left-0 w-full h-full bg-black/20 flex flex-col items-center justify-center z-10">
              <div class="text-center text-sm text-[#fff] font-bold">正在获取视频流，请稍等...，请勿关闭页面，否则视频流将无法正常显示</div>
              <div class="text-center text-sm text-[#fff] font-bold">如果长时间无法获取视频流，请检查高拍仪是否正常连接，或者重启高拍仪，关闭页面后重新打开</div>
            </div>
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleStartVideo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon_start.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">重开视频</div>
            </div>
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleStopVideo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon_stop.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">关闭视频</div>
            </div>
            <!-- <div class="flex flex-col items-center justify-center mr-4 cursor-pointer">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon-refresh.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">刷新</div>
            </div> -->
            <div class="flex flex-col items-center justify-center w-20 cursor-pointer" @click="handleZoomIn">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon_enlarge.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">点击放大</div>
            </div>
            <div class="flex flex-col items-center justify-center w-20 cursor-pointer" @click="handleZoomOut">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon_narrow.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">点击缩小</div>
            </div>
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleChangeVideo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-5" src="/assets/image/icon_toggle_camera.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">切换摄像头</div>
            </div>
          </div>
          <div class="w-40 bg-blue-200/15 p-4 box-border ml-4 rounded flex items-center justify-center">
            <div v-if="!isMaskShow" class="absolute top-0 left-0 w-full h-full bg-black/20"></div>
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleTakePicture">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon-camer.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">开始读取</div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-[1] ml-3 relative">
        <div>
          <div
            class="flex bg-blue-200/15 px-4 h-16 box-border rounded items-center justify-start text-base text-[#333] font-bold">
            图片展示区
          </div>
        </div>
        <div class="absolute top-[76px] left-0 bottom-[108px] w-full bg-blue-200/15 rounded">
          <div class="flex flex-wrap p-4 rounded">
            <el-image alt="点击预览" v-for="(item, index) in base64PicturesList" :key="index" :src="item" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" :preview-src-list="base64PicturesList" :initial-index="4" fit="cover"
              class="cursor-pointer rounded" />
          </div>
          <div v-if="currentTitle" class="text-center text-sm text-[#333] font-bold mt-4">
            当前操作： {{ currentTitle }}
          </div>
        </div>
        <div class="flex justify-between absolute bottom-0 left-0 right-0">
          <div class="flex flex-1 bg-blue-200/15 p-4 box-border rounded items-center justify-end">
            <div v-if="!isMaskShow" class="absolute top-0 left-0 w-full h-full bg-black/20 flex flex-col items-center justify-center z-10">
              <div class="text-center text-sm text-[#fff] font-bold">请勿关闭页面，否则视频流将无法正常显示</div>
            </div>
            <div class="flex flex-col items-center justify-center w-20 cursor-pointer" @click="handleShowInfo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon-info.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">读取信息</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import VideoDeviceControl from "../../utils/control";
import WebSocketConnection from "../../utils/scoket";

let wsConnection; // 连接
let videoControl; // 视频控制

const openSocket = () => {
  wsConnection = new WebSocketConnection("ws://127.0.0.1:3417"); // 连接
  videoControl = new VideoDeviceControl(wsConnection); // 视频控制
};

// 打开socket
openSocket();

const videoCanvas = ref(null); // 视频画布
const isConnected = ref(false); // 连接状态
const resolutionList = ref([]); // 分辨率列表
const resolutionValue = ref(""); // 分辨率值
const resolutionResult = ref(""); // 分辨率结果
const modeList = ref([]); // 模式列表
const modeValue = ref(""); // 模式值
const base64PicturesList = ref([]); // 图片列表
const angleValue = ref(""); // 角度值
const started = ref(false); // 开始状态
const actionValue = ref(""); // 操作值
const currentTitle = ref(""); // 当前标题
const isMaskShow = ref(false); // 遮罩层
let loading = null; // 加载状态

// 更新分辨率函数
const updateResolution = (result) => {
  handleActionChange("更新分辨率"); // 更新操作值
  const selectedMode = modeList.value.find(
    (mode) => mode.name === modeValue.value // 查找当前选择的模式
  );
  if (selectedMode) {
    resolutionList.value = selectedMode.res; // 更新分辨率列表
    resolutionList.value.map((item) => {
      if (item.width == result.width && item.height == result.height) {
        resolutionValue.value = `${item.width}x${item.height}`; // 设置分辨率值
        handleResolutionChange(); // 调用分辨率变化处理函数
      }
    });
  }
};

// 选择模式
const handleModeChange = () => {
  handleActionChange("选择模式");
  updateResolution(resolutionResult.value);
};

// 选择分辨率
const handleResolutionChange = () => {
  // 设置分辨率
  videoControl.setResolution({
    type: modeValue.value,
    width: parseInt(resolutionValue.value.split("x")[0]),
    height: parseInt(resolutionValue.value.split("x")[1]),
  });
};

// 设置分辨率回调
videoControl.setResolutionCallback((result) => {
  if (result) {
    resolutionResult.value = result; // 设置分辨率结果
    modeList.value = result.content; // 设置模式列表
    modeValue.value = modeList.value[1].name; // 默认选择第一个模式
    updateResolution(resolutionResult.value); // 初始更新分辨率
    ElMessage.success("高拍仪打开成功");
    handleActionChange("高拍仪打开成功");
  } else {
    ElMessage.error("高拍仪打开失败");
    handleActionChange("高拍仪打开失败");
  }
});

// 拍照
const handleTakePicture = () => {
  loading = ElLoading.service({
    lock: true,
    text: "拍照中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  handleActionChange("开始读取");
  videoControl.takePictureBase64();
};

videoControl.setBase64PictureCallback((result) => {
  console.log(result);
  loading.close();
  if (result) {
    base64PicturesList.value = ["data:image/jpg;base64," + result.pic];
    ElMessage.success("拍照成功");
  } else {
    ElMessage.error("拍照失败");
  }
});

videoControl.setVideoFrameCallback((isImageLoaded) => {
  isMaskShow.value = isImageLoaded;
});

const handleStartVideo = () => {
  videoControl.startVideo();
  handleActionChange("重开视频");
};

const handleStopVideo = () => {
  videoControl.stopVideo();
  handleActionChange("关闭视频");
};

const handleZoomIn = () => {
  videoControl.setZoomIn();
  handleActionChange("放大视频");
};

const handleZoomOut = () => {
  videoControl.setZoomOut();
  handleActionChange("缩视频小");
};

const handleChangeVideo = () => {
  videoControl.changeVideo();
  handleActionChange("切换摄像头");
};

const handleAngleChange = (value) => {
  videoControl.setAngle(Number(value));
  handleActionChange("设置图片角度");
};

const handleMouseMove = (event) => {
  handleActionChange("鼠标移动视频");
  const { pageX, pageY, target } = event;
  const loc = getPointOnCanvas(target, pageX, pageY);

  if (started.value) {
    if (videoControl.bSelected) {
      videoControl.setMouseRect(selX1, selY1, loc.x, loc.y);
    } else {
      videoControl.setMovePoint(loc.x, loc.y);
    }
  }
};

const handleMouseLeave = () => {
  started.value = false;
  handleActionChange("鼠标离开视频");
};

const handleMouseDown = (event) => {
  handleActionChange("鼠标按下视频");
  const { x, y } = event;
  const canvas = event.target;
  const loc = getPointOnCanvas(canvas, x, y);

  if (videoControl.bSelected) {
    selX1 = loc.x;
    selY1 = loc.y;
    videoControl.setMouseRect(selX1, selY1, loc.x, loc.y);
  } else {
    videoControl.setOffsetPoint(loc.x, loc.y);
  }

  started.value = true;
};

const handleMouseUp = (event) => {
  handleActionChange("鼠标松开视频");
  if (started.value) {
    handleMouseMove(event);
    started.value = false;
  }
};

const getPointOnCanvas = (canvas, x, y) => {
  const bbox = canvas.getBoundingClientRect();
  return {
    x: x - bbox.left * (canvas.width / bbox.width),
    y: y - bbox.top * (canvas.height / bbox.height),
  };
};

const handleActionChange = (value) => {
  actionValue.value = value;
};

const handleShowInfo = () => {
  handleActionChange("正在识别信息");
  console.log("handleShowInfo");
  // 判断是否存在
  if (base64PicturesList.value.length > 0) {
    // 获取iframe的父窗口
    const parentWindow = window.parent;

    // 构造要发送的数据
    var data = {
      action: "scannerBase64Img",
      message: base64PicturesList.value,
    };
    // 发送消息
    parentWindow.postMessage(JSON.stringify(data), "*");
  } else {
    console.log("base64PicturesList.value", base64PicturesList.value);
    ElMessage.error("请先拍照");
  }
};



const getFromURL = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const token = urlParams.get("token");
  const title = urlParams.get("title");
  currentTitle.value = title;
};

onMounted(() => {
  // 获取参数
  getFromURL();

  // 连接
  wsConnection.onMessage = (data) => {
    videoControl.handleMessage(data);
  };

  wsConnection.onOpen = () => {
    isConnected.value = true;
    console.log("wsConnection.onOpen");
    handleActionChange("连接成功");
    handleStopVideo();
    handleStartVideo();
  };

  wsConnection.onClose = () => {
    isConnected.value = false;
    handleActionChange("连接断开");
    if (wsConnection.socket.readyState !== WebSocket.OPEN) {
      wsConnection.connect();
    }
  };

  wsConnection.connect();

  if (videoCanvas.value) {
    videoControl.setCanvas(videoCanvas.value);
  }
});

onUnmounted(() => {
  if (wsConnection) {
    wsConnection.close();
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
